package com.teamwings.config.filter;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Pattern;

public class AutoFormWrapper extends HttpServletRequestWrapper {
	HttpServletRequest orgRequest = null;
	private Map<String, String[]> parameterMap;
	// 用于保存读取body中数据
	private final byte[] body;

	/**
	 * 预编译Pattern
	 */
	private static final Pattern SCRIPT_PATTERN_1 = Pattern.compile("<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
	private static final Pattern SCRIPT_PATTERN_2 = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
	private static final Pattern SCRIPT_PATTERN_3 = Pattern.compile("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
	private static final Pattern SCRIPT_PATTERN_4 = Pattern.compile("<[\r\n| | ]*script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
	private static final Pattern SCRIPT_PATTERN_5 = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
	private static final Pattern SCRIPT_PATTERN_6 = Pattern.compile("e-xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
	private static final Pattern SCRIPT_PATTERN_7 = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
	private static final Pattern SCRIPT_PATTERN_8 = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
	private static final Pattern SCRIPT_PATTERN_9 = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

	private static final String[] XSS_STR = "'|and |exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|or |+".split("\\|");

	public AutoFormWrapper(HttpServletRequest request) throws IOException {
		super(request);
		orgRequest = request;
		parameterMap = request.getParameterMap();
		body = StreamUtils.copyToByteArray(request.getInputStream());
	}

	// 重写几个HttpServletRequestWrapper中的方法

	/**
	 * 获取所有参数名
	 * @return 返回所有参数名
	 */
	@Override
	public Enumeration<String> getParameterNames() {
		Vector<String> vector = new Vector<>(parameterMap.keySet());
		return vector.elements();
	}

	/**
	 * 覆盖getParameter方法，将参数名和参数值都做xss & sql过滤。
	 * 如果需要获得原始的值，则通过super.getParameterValues(name)来获取
	 * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
	 */
	@Override
	public String getParameter(String name) {
		String[] results = parameterMap.get(name);
		if (results == null || results.length <= 0) {
			return null;
		} else {
			String value = results[0];
			if (value != null) {
				value = xssEncode(value);
			}
			return value;
		}
	}

	/**
	 * 获取指定参数名的所有值的数组，如：checkbox的所有数据 接收数组变量 ，如checkbox类型
	 */
	@Override
	public String[] getParameterValues(String name) {
		String[] results = parameterMap.get(name);
		if (results == null || results.length <= 0) {
			return null;
		} else {
			int length = results.length;
			for (int i = 0; i < length; i++) {
				results[i] = xssEncode(results[i]);
			}
			return results;
		}
	}

	/**
	 * 覆盖getHeader方法，将参数名和参数值都做xss & sql过滤。
	 * 如果需要获得原始的值，则通过super.getHeaders(name)来获取
	 * getHeaderNames 也可能需要覆盖
	 */
	@Override
	public String getHeader(String name) {
		String value = super.getHeader(xssEncode(name));
		if (value != null) {
			value = xssEncode(value);
		}
		return value;
	}

	/**
	 * 将容易引起xss & sql漏洞的半角字符直接替换成全角字符
	 * @param s 字符串
	 * @return 替换后新字符串
	 */
	private static String xssEncode(String s) {
		if (s == null || s.isEmpty()) {
			return s;
		} else {
			s = stripXssAndSql(s);
		}
		StringBuilder sb = new StringBuilder(s.length() + 16);
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
				case '>':
					// 转义大于号
					sb.append("＞");
					break;
				case '<':
					// 转义小于号
					sb.append("＜");
					break;
			    case '\'':
				    // 转义单引号
				    sb.append("＇");
				    break;
				// case '\"':
				// sb.append("＂");// 转义双引号
				// break;
				case '&':
					// 转义&
					sb.append("＆");
					break;
				case '#':
					// 转义#
					sb.append("＃");
					break;
				default:
					sb.append(c);
					break;
			}
		}
		return sb.toString();
	}

	/**
	 * 获取最原始的request
	 * @return HttpServletRequest
	 */
	public HttpServletRequest getOrgRequest() {
		return orgRequest;
	}

	/**
	 * 获取最原始的request的静态方法
	 * @return HttpServletRequest
	 */
	public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
		if (req instanceof AutoFormWrapper) {
			return ((AutoFormWrapper) req).getOrgRequest();
		}

		return req;
	}

	/**
	 * 防止xss跨脚本攻击（替换，根据实际情况调整）
	 */
	public static String stripXssAndSql(String value) {
		if (value != null) {
			value = SCRIPT_PATTERN_1.matcher(value).replaceAll("");
			// Avoid anything in a
			// src="http://www.yihaomen.com/article/java/..." type of
			// e-xpression
			value = SCRIPT_PATTERN_2.matcher(value).replaceAll("");
			// Remove any lonesome </script> tag
			value = SCRIPT_PATTERN_3.matcher(value).replaceAll("");
			// Remove any lonesome <script ...> tag
			value = SCRIPT_PATTERN_4.matcher(value).replaceAll("");
			// Avoid eval(...) expressions
			value = SCRIPT_PATTERN_5.matcher(value).replaceAll("");
			// Avoid e-xpression(...) expressions
			value = SCRIPT_PATTERN_6.matcher(value).replaceAll("");
			// Avoid javascript:... expressions
			value = SCRIPT_PATTERN_7.matcher(value).replaceAll("");
			// Avoid vbscript:... expressions
			value = SCRIPT_PATTERN_8.matcher(value).replaceAll("");
			// Avoid onload= expressions
			value = SCRIPT_PATTERN_9.matcher(value).replaceAll("");
		}
		return value;
	}

	/**
	 * 过滤参数
	 * @param value 参数
	 * @return -
	 */
	public boolean checkXssAndSql(String value) {
		boolean flag = false;
		if (value != null) {
			// NOTE: It's highly recommended to use the ESAPI library and
			// uncomment the following line to
			// avoid encoded attacks.
			// value = ESAPI.encoder().canonicalize(value);
			// Avoid null characters
			/** value = value.replaceAll("", ""); ***/
			// Avoid anything between script tags
			flag = SCRIPT_PATTERN_1.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Avoid anything in a
			// src="http://www.yihaomen.com/article/java/..." type of
			// e-xpression
			flag = SCRIPT_PATTERN_2.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Remove any lonesome </script> tag
			flag = SCRIPT_PATTERN_3.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Remove any lonesome <script ...> tag
			flag = SCRIPT_PATTERN_4.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Avoid eval(...) expressions
			flag = SCRIPT_PATTERN_5.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Avoid e-xpression(...) expressions
			flag = SCRIPT_PATTERN_6.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Avoid javascript:... expressions
			flag = SCRIPT_PATTERN_7.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Avoid vbscript:... expressions
			flag = SCRIPT_PATTERN_8.matcher(value).find();
			if (flag) {
				return flag;
			}
			// Avoid onload= expressions
			flag = SCRIPT_PATTERN_9.matcher(value).find();
			if (flag) {
				return flag;
			}
			// sql注入过滤
			String v = value.toLowerCase();
			// String[] xssArr = XSS_STR;
			for (String s : XSS_STR) {
				if (v.contains(s)) {
					flag = true;
					return flag;
				}
			}
		}
		return flag;
	}

	public final boolean checkParameter() {
		Map<String, String[]> submitParams = new HashMap<>(parameterMap);
		Set<String> submitNames = submitParams.keySet();
		for (String submitName : submitNames) {
			Object submitValues = submitParams.get(submitName);
			if ((submitValues != null)) {
				for (String submitValue : (String[]) submitValues) {
					if (checkXssAndSql(submitValue)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body);
		return new ServletInputStream() {

			@Override
			public int read() throws IOException {
				return bais.read();
			}

			@Override
			public boolean isFinished() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isReady() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void setReadListener(ReadListener arg0) {
				// TODO Auto-generated method stub

			}
		};
	}
}
